package xc.src.syn;

//不安全的买票
public class BuyTicket implements Runnable {
    private int ticketNums = 10;
    boolean flag = true;//外部停止方式

    @Override
    public void run() {
        //买票
        while (flag) {
            buy();
        }
    }

    //判断是否有票
    //同步方法，锁的是this
    private synchronized void buy() {
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }

    //线程不安全
    public static class UnsafeBuyTicket{
        public static void main(String[] args) {
            BuyTicket station =new BuyTicket();

            new Thread(station,"苦逼的我").start();
            new Thread(station,"牛逼的我").start();
            new Thread(station,"可恶的我").start();
        }
    }
}
